package com.coexist.listnotes;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Text;

@PersistenceCapable
public class Item {
   @PrimaryKey
   @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
   private Key key;

   @Persistent
   private String name;

   @Persistent
   private Text details;

   @Persistent
   private Key parentKey;

   @Persistent
   private Integer index;

   public Item(String pName, Text pDetails, Key pParentKey) {
      name = pName;
      details = pDetails;
      parentKey = pParentKey;
      Item[] siblings = getParentItem().getChildren();
      index = siblings[siblings.length - 1].getIndex() + 1;
   }

   public Key getKey() {
      return key;
   }

   public String getName() {
      return name;
   }

   public void setName(String pName) {
      name = pName;
   }

   public Text getDetails() {
      return details;
   }

   public void setDetails(Text pDetails) {
      details = pDetails;
   }

   public Key getParentKey() {
      return parentKey;
   }

   public void setParentKey(Key pParent) {
      parentKey = pParent;
   }

   public Item getParentItem() {
      PersistenceManager pm = PMF.get().getPersistenceManager();
      return pm.getObjectById(Item.class, parentKey);
   }

   public Integer getIndex() {
      return index;
   }

   @SuppressWarnings("unchecked")
   public Item[] getChildren(String pOrderBy) {
      PersistenceManager pm = PMF.get().getPersistenceManager();
      Query query = pm.newQuery(Item.class);
      query.setFilter("parentKey == key");
      query.setOrdering(pOrderBy);
      query.declareParameters("Key key");
      try {
         return ((List<Item>) query.execute(key)).toArray(new Item[0]);
      } finally {
         pm.close();
      }
   }

   public Item[] getChildren() {
      return getChildren("index");
   }

   public void delete() {
      PersistenceManager pm = PMF.get().getPersistenceManager();
      Transaction tx = pm.currentTransaction();
      try {
         tx.begin();
         for (Item child : getChildren()) {
            child.delete();
            pm.deletePersistent(child);
         }
         pm.deletePersistent(this);
         tx.commit();
      } finally {
         if (tx.isActive()) {
            tx.rollback();
         }
      }
   }
}
